package com.live.shop.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.live.shop.R;
import com.live.shop.model.CommentModel;
import com.live.shop.model.KeywordModel;
import com.live.shop.model.KeywordRecordModel;
import com.live.shop.model.MusicModel;
import com.live.shop.model.PrologueModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.CommentsListDatabase;
import com.live.shop.sql.KeywordListDatabase;
import com.live.shop.sql.MusicListDatabase;
import com.live.shop.sql.PrologueListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;
import com.live.shop.view.ToastBottomUtils;

import java.io.IOException;
import java.util.List;
import java.util.Random;

public class SuspendedWindowService extends Service {
    WindowManager.LayoutParams params;
    WindowManager windowManager;

    LinearLayout window_linearlayout_all;
    LinearLayout window_linearlayout;

    ImageView window_imageview;
    LinearLayout window_button_linearlayout;
    //评论
    ImageView window_comment_status;
    TextView window_comment_txt;
    //关键词
    LinearLayout window_keyword_linearlayout;
    ImageView window_keyword_imageview;
    TextView window_keyword_textview;
    //开场白
    LinearLayout window_prologue_linearlayout;
    ImageView window_prologue_imageview;
    TextView window_prologue_textview;
    //音乐
    LinearLayout window_music_linearlayout;
    ImageView window_music_imageview;
    TextView window_music_textview;

    LinearLayout window_close_linearlayout;
    //自身服务ID
    int windowStartId;
    //开场白状态
    boolean prologuesStatue = false;
    int prologuePlayCurrentPosition = -1;//播放位置
    MediaPlayer prologuePlayer;
    //关键词状态
    boolean keywordStatue = false;
    MediaPlayer keywordPlayer;
    //音乐状态
    boolean musicStatue = false;
    MediaPlayer musicPlayer;

    UserDatabase userDb;
    KeywordListDatabase keyDb;
    PrologueListDatabase proDb;
    MusicListDatabase musicDb;
    CommentsListDatabase comDb;
    UserModel userModel;
    List<KeywordModel> keyList;
    List<PrologueModel> proList;
    List<MusicModel> musicList;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        windowStartId = startId;
        return super.onStartCommand(intent, flags, startId);
    }
    //广播接收评论
    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent != null){
                String userCom = intent.getStringExtra("userCom");
                String userName = intent.getStringExtra("userName");
                int type = intent.getIntExtra("type",0);
                startTask(userName,userCom,type);
            }
        }
    };

    private void startTask(String userName,String userCom,int type){

        window_comment_txt.setText(userName + "：" + userCom);

        //是否开启回复
        if (keywordStatue) {
            int comid = 0;
            //保留评论
            if (userModel.getCommentKeep() == 1) {
                comid = (int)comDb.insertData2(userName,userCom,type,0,"");
            }
            String filePath = "";
            int keyPosition = -1;
            //查询评论是否包含该关键词
            boolean isHasKey = false;
            //第一步：先匹配回复
            for (int a = 0 ; a < keyList.size();a++) {
                String[] kws = keyList.get(a).getKeyword().split("\\|");
                for (String k:kws) {
                    //是否包含该关键词
                    if(userCom.contains(k)){
                        isHasKey = true;
                        keyPosition = a;//当前该关键词位置
                        comDb.updateKeywordId(comid,keyList.get(a).getKeywordId(),2);
                        break;
                    }
                }
                if(isHasKey) break;
            }
            if(!isHasKey){
                //没有匹配到关键词  keyword_mate 匹配状态 0未匹配 1无匹配 2 有匹配
                comDb.updateKeywordId(comid,0,1);
                return;
            }
            //第二步：判断当前是否正在回复
            if(keywordPlayer != null) return;
            //判断是否开场白正在播放并且是可以打断
            if(prologuePlayer != null){
                //不允许打断
                if( userModel.getPrologueBreak() == 0) return;
                //允许打断 判断打断的话术是否从开头播放 0不是（续播，记录播放的时间） 1是
                if(userModel.getPrologueRestart() == 0){
                    //开场白允许打断，【暂停】播放
                    prologuePlayer.pause();
                    //获取当前播放位置
                    prologuePlayCurrentPosition = prologuePlayer.getCurrentPosition();
                }else{
                    //开场白不允许打断，【停止】播放
                    prologuePlayer.release();
                    prologuePlayer = null;
                }
            }

            int recordPosition = -1;
            int minPlayNum = -1;//最小播放次数
            List<KeywordRecordModel> recordList = keyList.get(keyPosition).getListRecord();
            if(userModel.getProloguePlaytype() == 1){
                //随机
                int randomNum = 0;
                if(recordList.size() != 1){
                    Random random = new Random();
                    randomNum = random.nextInt(recordList.size());
                }
                filePath = recordList.get(randomNum).getAnswerAudio();
                recordPosition = randomNum;
            }else{
                //轮播
                for (int b = 0 ; b < recordList.size();b++) {
                    if(minPlayNum == -1){
                        minPlayNum = recordList.get(b).getUseNum();
                        filePath = recordList.get(b).getAnswerAudio();
                        recordPosition = b;
                    }else{
                        if (recordList.get(b).getUseNum() < minPlayNum) {
                            minPlayNum = recordList.get(b).getUseNum();
                            filePath = recordList.get(b).getAnswerAudio();
                            recordPosition = b;
                        }
                    }
                }
            }
            comDb.updateKeywordReply(comid,1);
            KeywordPlay(filePath,keyPosition,recordPosition);
        }
    }
    //播放问答关键词
    private void KeywordPlay(String filePath,int keyPosition,int recordPosition) {
        if(keyPosition != -1)keyList.get(keyPosition).setUseNum(keyList.get(keyPosition).getUseNum()+1);
        if(recordPosition != -1)keyList.get(keyPosition).getListRecord().get(recordPosition).setUseNum(keyList.get(keyPosition).getListRecord().get(recordPosition).getUseNum()+1);

        if(recordPosition != -1 && FileUtils.getFileExist(getApplicationContext(),filePath)){
            //问答找到了 文件路径不为空，且开始播放
            try {
                keywordPlayer = new MediaPlayer();
                keywordPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                if(musicPlayer != null){
                    float volume = 0.2f; // 设置音量为20%，左右声道的音量都为20%
                    musicPlayer.setVolume(volume,volume);
                }
                keywordPlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                keywordPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        keywordPlayer = null;
                        if(userModel.getKeywordKeeptype() == 1){
                            //开启评论记忆回复
                            CommentModel model = comDb.selectKeywordMateOld(2);
                            if(model.getKeywordId() != 0 && keywordStatue){
                                //存在未回复，开始回复
                                startKeywordKeep(model);
                                return;
                            }
                        }
                        //是否进行继续播放
                        if(prologuePlayCurrentPosition != -1 && prologuePlayer != null){
                            prologuePlayer.seekTo(prologuePlayCurrentPosition);
                            prologuePlayer.start();
                            prologuePlayCurrentPosition = -1;
                        }else{
                            if(musicPlayer != null){
                                float volume = 1.0f; // 设置音量为100%(最大音量)，左右声道的音量都为50%
                                musicPlayer.setVolume(volume,volume);
                            }
                            //打断的话术是否重新播放 0不是（续播，记录播放的时间） 1是
                            if(userModel.getPrologueRestart() == 1 && prologuePlayer == null){
                                ProloguePlay();
                            }
                        }
                    }
                });
                keywordPlayer.prepare();
                keywordPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //开启评论记忆回复
    public void startKeywordKeep(CommentModel model){
        int keyPosition = -1;
        String filePath = "";
        int recordPosition = -1;
        int minPlayNum = -1;//最小播放次数
        for (int a = 0 ;a < keyList.size() ; a++) {
            if (model.getKeywordId() == keyList.get(a).getKeywordId()){
                keyPosition = a;
                break;
            }
        }
        List<KeywordRecordModel> recordList = keyList.get(keyPosition).getListRecord();
        if(userModel.getProloguePlaytype() == 1){
            //随机
            int randomNum = 0;
            if(recordList.size() != 1){
                Random random = new Random();
                randomNum = random.nextInt(recordList.size());
            }
            filePath = recordList.get(randomNum).getAnswerAudio();
            recordPosition = randomNum;
        }else{
            //轮播
            for (int b = 0 ; b < recordList.size();b++) {
                if(minPlayNum == -1){
                    minPlayNum = recordList.get(b).getUseNum();
                    filePath = recordList.get(b).getAnswerAudio();
                    recordPosition = b;
                }else{
                    if (recordList.get(b).getUseNum() < minPlayNum) {
                        minPlayNum = recordList.get(b).getUseNum();
                        filePath = recordList.get(b).getAnswerAudio();
                        recordPosition = b;
                    }
                }
            }
        }
        comDb.updateKeywordReply(model.getCommentsId(),1);
        KeywordPlay(filePath,keyPosition,recordPosition);
    }
    //播放开场白
    private void ProloguePlay() {
        //关闭状态
        if(!prologuesStatue) return;

        String filePath = "";
        int minPlayNum = -1;
        int position = -1;
        if(userModel.getProloguePlaytype() == 1){
            //随机
            int randomNum = 0;
            if(proList.size() != 1){
                Random random = new Random();
                randomNum = random.nextInt(proList.size());
            }
            filePath = proList.get(randomNum).getPrologueAudio();
            position = randomNum;
        }else{
            //轮播
            for (int i = 0 ; i < proList.size();i++) {
                if(minPlayNum == -1){
                    minPlayNum = proList.get(i).getUseNum();
                    filePath = proList.get(i).getPrologueAudio();
                    position = i;
                }else{
                    if (proList.get(i).getUseNum() < minPlayNum) {
                        minPlayNum = proList.get(i).getUseNum();
                        filePath = proList.get(i).getPrologueAudio();
                        position = i;
                    }
                }
            }
        }
        //增加次数
        proList.get(position).setUseNum(proList.get(position).getUseNum()+1);
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            try {
                Handler h1 = new Handler(Looper.getMainLooper());
                prologuePlayer = new MediaPlayer();
                prologuePlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                if(musicPlayer != null){
                    float volume = 0.2f; // 设置音量为20%，左右声道的音量都为20%
                    musicPlayer.setVolume(volume,volume);
                }
                prologuePlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                prologuePlayer.prepareAsync();
                prologuePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        // 媒体文件准备好后，设置延迟播放
                        h1.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if(prologuePlayer != null){
                                    prologuePlayer.start();
                                }
                            }
                        }, userModel.getPrologueInterval() * 1000); // 延迟10秒
                    }
                });
                prologuePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        prologuePlayer = null;
                        if(musicPlayer != null){
                            float volume = 1.0f; // 设置音量为100%(最大音量)，左右声道的音量都为50%
                            musicPlayer.setVolume(volume,volume);
                        }
                        ProloguePlay();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //播放背景音乐
    private void MusicPlay() {
        String filePath = "";
        int minPlayNum = -1;
        int position = -1;
        for (int i = 0 ; i < musicList.size();i++) {
            if(minPlayNum == -1){
                minPlayNum = musicList.get(i).getPlayNum();
                filePath = musicList.get(i).getMusicUrl();
                position = i;
            }else{
                if (musicList.get(i).getPlayNum() < minPlayNum) {
                    minPlayNum = musicList.get(i).getPlayNum();
                    filePath = musicList.get(i).getMusicUrl();
                    position = i;
                }
            }
        }
        musicList.get(position).setPlayNum(musicList.get(position).getPlayNum()+1);
        if(FileUtils.getFileExist(getApplicationContext(),filePath)){
            musicPlayer = new MediaPlayer();
            musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            try {
                musicPlayer.setDataSource(getApplicationContext(), Uri.parse(filePath));
                musicPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.release();
                        mediaPlayer = null;
                        MusicPlay();
                    }
                });
                musicPlayer.prepare();
                musicPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    public void onCreate() {
        super.onCreate();
        //加载view
        createToucher();
        keyDb = new KeywordListDatabase(getApplicationContext());
        proDb = new PrologueListDatabase(getApplicationContext());
        musicDb = new MusicListDatabase(getApplicationContext());
        comDb = new CommentsListDatabase(getApplicationContext());
        userDb = new UserDatabase(getApplicationContext());
        keyList = keyDb.selectAllStatusYes();
        proList = proDb.selectAllStatusYes();
        musicList = musicDb.selectUseNum0();
        userModel = userDb.select();

        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter("AccessibilityServiceComment");
        registerReceiver(broadcastReceiver, intentFilter);

        //快手
        if(userModel.getFunctionId() == 3){
            startService(new Intent(getApplicationContext(), KuaiShouService.class));
        }
        //震动
        GetUtil.getVibrator(getApplicationContext());
    }
    //布局View实例化
    private void createToucher() {
        params = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        // 设置效果为背景透明.
        params.format = PixelFormat.RGBA_8888;
        // 设置flags,可触焦
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //此窗口不会获得关键输入焦点,该窗口不需要与软输入法进行交互,取消可以正常显示，但是系统的返回键用不了
        //params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 设置窗口初始停靠位置.
        params.gravity = Gravity.LEFT | Gravity.CENTER;
        params.x = 0;
        params.y = 0;

        // 设置悬浮窗口长宽.根据内容显示
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        // 获取浮动窗口视图所在布局.
        window_linearlayout_all = (LinearLayout) inflater.inflate(R.layout.service_window_layout, null);
        // 添加
        windowManager.addView(window_linearlayout_all, params);
        // 主动计算出当前View的宽高信息.
        window_linearlayout_all.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        window_linearlayout = window_linearlayout_all.findViewById(R.id.window_linearlayout);
        window_imageview = window_linearlayout_all.findViewById(R.id.window_imageview);
        window_button_linearlayout = window_linearlayout_all.findViewById(R.id.window_button_linearlayout);
        window_keyword_linearlayout = window_linearlayout_all.findViewById(R.id.window_keyword_linearlayout);
        window_comment_status = window_linearlayout_all.findViewById(R.id.window_comment_status);
        window_comment_txt = window_linearlayout_all.findViewById(R.id.window_comment_txt);
        window_keyword_imageview = window_linearlayout_all.findViewById(R.id.window_keyword_imageview);
        window_keyword_textview = window_linearlayout_all.findViewById(R.id.window_keyword_textview);
        window_prologue_linearlayout = window_linearlayout_all.findViewById(R.id.window_prologue_linearlayout);
        window_prologue_imageview = window_linearlayout_all.findViewById(R.id.window_prologue_imageview);
        window_prologue_textview = window_linearlayout_all.findViewById(R.id.window_prologue_textview);
        window_music_linearlayout = window_linearlayout_all.findViewById(R.id.window_music_linearlayout);
        window_music_imageview = window_linearlayout_all.findViewById(R.id.window_music_imageview);
        window_music_textview = window_linearlayout_all.findViewById(R.id.window_music_textview);
        window_close_linearlayout = window_linearlayout_all.findViewById(R.id.window_close_linearlayout);

        //窗口移动监听
        window_imageview.setOnTouchListener(new View.OnTouchListener() {
            private int x;
            private int y;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        x = (int) event.getRawX();
                        y = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int nowX = (int) event.getRawX();
                        int nowY = (int) event.getRawY();
                        int movedX = nowX - x;
                        int movedY = nowY - y;
                        x = nowX;
                        y = nowY;
                        params.x = params.x + movedX;
                        params.y = params.y + movedY;
                        windowManager.updateViewLayout(window_linearlayout_all, params);
                        break;
                }
                return false;
            }
        });
        //加载点击事件
        initViewClick();
        //设置初始状态
        setViewStatus();
    }
    //加载点击事件
    private void initViewClick(){
        //展开或关闭
        window_imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (window_button_linearlayout.getVisibility() == View.VISIBLE) {
                    //则关闭
                    window_button_linearlayout.setVisibility(View.GONE);
                    window_imageview.setImageResource(R.mipmap.icon_service_window_show);
                } else {
                    //则展示
                    window_button_linearlayout.setVisibility(View.VISIBLE);
                    window_imageview.setImageResource(R.mipmap.icon_service_window_back);
                }
            }
        });
        //点击关键词
        window_keyword_linearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(keyList.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未添加关键词！");
                    return;
                }
                if(keywordStatue){
                    setKeywordStatus(false);
                }else{
                    setKeywordStatus(true);
                }
            }
        });
        //点击开场白
        window_prologue_linearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(proList.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未添加开场白！");
                    return;
                }
                if(prologuesStatue){
                    setPrologueStatus(false);
                }else{
                    setPrologueStatus(true);
                }
            }
        });
        //点击音乐
        window_music_linearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(musicList.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未添加背景音乐！");
                    return;
                }
                if(musicStatue){
                    setMusicStatus(false);
                }else{
                    setMusicStatus(true);
                }
            }
        });
        //关闭本服务
        window_close_linearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭服务
                stopSelf(windowStartId);
            }
        });
    }
    //设置初始状态
    private void setViewStatus(){
        setKeywordStatus(keywordStatue);
        setPrologueStatus(prologuesStatue);
        setMusicStatus(musicStatue);
        if(GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.CommentService")){
            window_comment_status.setBackgroundResource(R.color.blue);
        }else{
            window_comment_status.setBackgroundResource(R.color.black);
        }
    }
    //设置关键词
    public void setKeywordStatus(boolean status){
        if(status){
            //设置开启
            keywordStatue = true;
            window_keyword_imageview.setImageResource(R.mipmap.toast_ok_icon);
            window_keyword_textview.setText("已开启回复");
        }else{
            //设置关闭
            keywordStatue = false;
            window_keyword_imageview.setImageResource(R.mipmap.toast_no_icon);
            window_keyword_textview.setText("已关闭回复");
            if(keywordPlayer != null){
                keywordPlayer.release();
                keywordPlayer = null;
            }
        }
    }
    //设置开场白
    public void setPrologueStatus(boolean status){
        if(status){
            //设置开启
            prologuesStatue = true;
            window_prologue_imageview.setImageResource(R.mipmap.toast_ok_icon);
            window_prologue_textview.setText("已开启话术");
            ProloguePlay();
        }else{
            //设置关闭
            prologuesStatue = false;
            window_prologue_imageview.setImageResource(R.mipmap.toast_no_icon);
            window_prologue_textview.setText("已关闭话术");
            if(prologuePlayer != null){
                prologuePlayer.release();
                prologuePlayer = null;
            }
        }
    }
    //设置音乐
    public void setMusicStatus(boolean status){
        if(status){
            //设置开启
            musicStatue = true;
            window_music_imageview.setImageResource(R.mipmap.toast_ok_icon);
            window_music_textview.setText("已开启音乐");
            MusicPlay();
        }else{
            //设置关闭
            musicStatue = false;
            window_music_imageview.setImageResource(R.mipmap.toast_no_icon);
            window_music_textview.setText("已关闭音乐");
            if(musicPlayer != null){
                musicPlayer.release();
                musicPlayer = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (window_linearlayout_all != null) {
            windowManager.removeView(window_linearlayout_all);
        }
        if(musicPlayer != null){
            musicPlayer.release();
        }
        if(prologuePlayer != null){
            prologuePlayer.release();
        }
        if(keywordPlayer != null){
            keywordPlayer.release();
        }
        //开场白状态
        prologuesStatue = false;
        //关键词状态
        keywordStatue = false;
        //音乐状态
        musicStatue = false;

        Intent intent = new Intent("HomeActivityStatus");
        intent.putExtra("window_status", "close");
        intent.putExtra("token_status", "close");
        sendBroadcast(intent);
        //取消注册广播接收器
        unregisterReceiver(broadcastReceiver);
        //关闭快手服务
        boolean iswork = GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.KuaiShouService");
        if(iswork){
            stopService(new Intent(getApplicationContext(), KuaiShouService.class));
        }
        //设置播放数据
        keyDb.updateUseNumData(keyList);
        musicDb.updatePlayNumData(musicList);
        proDb.updateUseNumData(proList);
        //震动
        GetUtil.getVibrator(getApplicationContext());
    }
}